package com.pisolution.actuator.client.registration;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.ServletContext;

/**
 * 适用于获取以 Servlet 容器方式启动的客户端应用程序信息.
 *
 * @author sora
 * @version 0.1.0
 */
public class ServletApplicationFactory extends ApplicationFactory {
    /** 获取上下文路径. */
    private final ServletContext ctx;

    // -------------------------------------------------------------------------------------------------
    //  初始化
    // -------------------------------------------------------------------------------------------------

    /**
     * 初始化 {@link ServletApplicationFactory}.
     *
     * @param cfg 用于读取应用名称等信息.
     * @param srv 用于获取应用启动端口等信息.
     * @param ctx 获取上下文路径.
     */
    public ServletApplicationFactory(final ApplicationConfig cfg, final ServerProperties srv, final ServletContext ctx) {
        super(cfg, srv);

        this.ctx = ctx;
    }

    // -------------------------------------------------------------------------------------------------
    //  应用信息
    // -------------------------------------------------------------------------------------------------

    @Override
    public String getEndpoint() {
        return UriComponentsBuilder
            .newInstance()
            .scheme(this.getScheme())
            .host(this.getHost())
            .port(super.port)
            .path(this.ctx.getContextPath())
            .toUriString();
    }
}
